package controllers

import (
	"encoding/json"
	beego "github.com/beego/beego/v2/server/web"
	"news_website_db/cache"
	"news_website_db/models"
)

type StaticController struct {
	beego.Controller
}

func (c *StaticController) Add() {
	user_id, _ := c.GetInt("user_id")
	new_id, _ := c.GetInt("new_id")
	contest := c.GetString("contest")
	var status models.Status
	status.UserId = user_id
	status.NewId = new_id
	status.Contest = contest
	if status.Add() != nil {
		c.Data["json"] = map[string]interface{}{
			"code": 500,
			"msg":  "添加失败",
		}
		c.ServeJSON()
		return
	}
	c.Data["json"] = map[string]interface{}{
		"code": 200,
		"msg":  "添加成功",
	}
	c.ServeJSON()
	return
}
func (c *StaticController) List() {
	c.Ctx.Output.Header("Access-Control-Allow-Origin", "*")
	page, _ := c.GetInt("page", 1)
	size, _ := c.GetInt("size", 5)
	var count int64
	models.DB.Model(&models.Status{}).Count(&count)
	offset := (page - 1) * size
	get, _ := cache.Rdb.Get(cache.Ctx, "redis_list").Result()
	var status []models.StstusData
	if get == "" {
		models.DB.Debug().
			Model(&models.Status{}).
			Offset(offset).Limit(size).
			Select("`statuses`.*, news.title,news.name,news.address,news.img").
			Joins("join news on statuses.new_id = news.id").
			Find(&status)
		JsonData, _ := json.Marshal(status)
		cache.Rdb.Set(cache.Ctx, "redis_list", JsonData, 0)
	} else {
		json.Unmarshal([]byte(get), &status)
	}
	c.Data["json"] = map[string]interface{}{
		"code":  200,
		"msg":   "查询成功",
		"data":  status,
		"page":  page,
		"size":  size,
		"count": count,
	}
	c.ServeJSON()
	return
}
